<template>
  <el-dialog :title="searchType === 'product' ? '选择商品' : ''" :visible.sync="showDialog" :before-close="closeDialog"
    :close-on-click-modal="false" width="1200px" top="100px">
    <el-row type="flex" justify="space-around">
      <el-col :span="24">
        <el-form class="search clearfix" :inline="true" label-suffix="：" size="mini" :model="search">
          <!-- 商品筛选条件 -->
          <el-row>
            <el-form-item>
              <el-select v-model="search.productType" class="w120" clearable disabled placeholder="全部类型"
                @change="getList('search')">
                <el-option v-for="item in options.type" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-select v-model="search.productStatus" class="w120" clearable placeholder="全部状态">
                <el-option v-for="item in options.productStatus" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-input v-model="search.productName" class="w300" clearable placeholder="搜索编码/名称/条码/助记码/别名"
                @keyup.enter.native="getList('search')">
                <el-button slot="append" icon="el-icon-search" @click="getList('search')" />
              </el-input>
            </el-form-item>
          </el-row>
        </el-form>
      </el-col>
    </el-row>
    <el-row type="flex" justify="space-around" class="border-bottom pb20">
      <el-col :span="4">
        <div v-if="searchType === 'product'" class="tree-header">分类筛选</div>
        <el-tree :data="searchType === 'product' ? options.category :[]"
          :props="{children: 'children', label: searchType === 'shop' ? 'groupName' : 'name'}"
          :expand-on-click-node="false" highlight-current default-expand-all @node-click="changeTreeNode" />
      </el-col>
      <el-col :span="20">
        <el-table v-if="searchType === 'product'" ref="productList" size="small" height="500" :data="list"
          :cell-style="$style.cellStyle" :header-cell-style="$style.rowClass" @select="selectRow"
          @select-all="selectAll">
          <el-table-column type="selection" :selectable="handleSelectable" width="55" />
          <el-table-column label="商品名称" prop="productName" />
          <el-table-column label="商品编码" prop="productCode" width="200" />
          <el-table-column label="规格单位" prop="unitName" />
          <el-table-column label="状态" prop="productStatus">
            <template slot-scope="{row}">
              <el-tag :type="options.productStatus[row.productStatus * 1].type">
                {{ options.productStatus[row.productStatus * 1].name }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>
        <pagination class="page tc mt10" :total="page.total" :page.sync="page.current" :limit.sync="page.size"
          @pagination="getList" />
      </el-col>
    </el-row>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" size="small" @click="getSelect()">确 定</el-button>
      <el-button size="small" @click="closeDialog()">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
class Search {
  constructor(type) {
    switch (type) {
      case 'product':
        this.productType = 0; // 商品类型(0.标准商品1.组合商品2.拆分商品3.分级商品)
        this.productStatus = ''; // 商品状态(0.正常1.停售2.淘汰3.删除)
        this.relCategory = ''; // 分类编号(一级分类或者二级分类)
        this.productName = ''; // 商品名称,商品编码,助记码,sku条码
        break;
    }
  }
}
class Page {
  constructor() {
    this.total = 0;
    this.current = 1;
    this.size = 10;
  }
}
class Options {
  constructor() {
    this.category = [];
    this.productStatus = [
      { id: 0, name: '正常', type: 'success' },
      { id: 1, name: '停售', type: 'danger' },
      { id: 2, name: '淘汰', type: 'warning' },
      { id: 3, name: '删除', type: 'info' }
    ]; // 商品状态
    this.type = [
      { id: 0, name: '标准商品' },
      { id: 1, name: '组合商品' },
      { id: 2, name: '拆分商品' },
      { id: 3, name: '分级商品' }
    ]; // 商品类型
  }
}
import {
  categoryCacheList,
  productListPage
} from '@/api/goods';
import pagination from '@/components/Pagination';
export default {
  name: 'Search',
  components: {
    pagination
  },
  props: {
    searchType: {
      type: String,
      default: 'product'
    }, // 搜索类型 category分类；product产品；shop门店
    selectMode: {
      type: String,
      default: 'single'
    }, // 选择模式，single 单选；multiple 多选
    showDialog: {
      type: Boolean,
      default: false
    }, // 开关
    defaultGoods: {
      type: Array,
      default: () => []
    }, // 默认回显数据
    showSelected: {
      type: Boolean,
      default: false
    } // 回显标识
  },
  data () {
    return {
      page: new Page(), // 列表分页
      search: new Search(this.searchType), // 列表搜索
      options: new Options(), // 搜索项
      list: [], // 商品列表
      preselection: [], // 筛选弹窗-商品预选
      selectedGoods: []
    };
  },
  watch: {
    showDialog (newVal) {
      if (newVal) {
        this.getOptions();
        this.open();
      }
    }
  },
  created () {
  },
  methods: {
    open () {
      this.selectedGoods = [];
      if (this.defaultGoods.length > 0) {
        this.selectedGoods = JSON.parse(JSON.stringify(this.defaultGoods));
      }
      this.checkedProduct();
    },
    // 用于已选商品进行回显
    checkedProduct () {
      if (this.showSelected) {
        const ids = this.selectedGoods.map(val => val.productId);
        this.list.forEach(item => {
          if (ids.includes(item.productId)) {
            this.$nextTick(() => {
              this.$refs['productList'].toggleRowSelection(item, true);
            });
          }
        });
      }
    },
    // 获取条件选项
    async getOptions () {
      this.options.category = [{ name: '全部分类', catid: '' }, ...await categoryCacheList()];
      this.getList();
    },
    // 获取商品列表
    async getList (type) {
      if (type === 'search') this.page = new Page();
      try {
        let data;
        if (this.searchType === 'product') {
          const params = { ...this.page, ...this.search };
          data = await productListPage(params);
        }
        const { records, total } = data;
        this.page.total = total * 1;
        this.list = records;
        this.checkedProduct();
      } catch (e) {
        this.page.total = 0;
        this.list = [];
      }
    },
    // 切换左侧分类
    changeTreeNode (val) {
      switch (this.searchType) {
        case 'product':
          this.search.relCategory = val.catid;
          break;
      }
      this.getList();
    },
    // 是否可选
    handleSelectable (row, index) {
      return row.isExist < 1 || !row.isExist;
    },
    // 当用户手动勾选数据行的 Checkbox 时触发的事件
    selectRow (selection, row) {
      const ids = selection.map(val => val.productId);
      if (ids.includes(row.productId)) {
        this.addSelectGood([row]);
      } else {
        this.delSelectGood([row]);
      }
    },
    // 当用户手动勾选全选 Checkbox 时触发的事件
    selectAll (selection) {
      if (selection.length <= 0) {
        this.delSelectGood(this.list);
      } else {
        this.addSelectGood(this.list);
      }
    },
    // 多选添加
    addSelectGood (arr) {
      const ids = this.selectedGoods.map(val => val.productId);
      arr.forEach(item => {
        if (!ids.includes(item.productId)) {
          this.selectedGoods.push(item);
        }
      });
    },
    // 多选删除
    delSelectGood (arr) {
      const ids = this.selectedGoods.map(val => val.productId);
      arr.forEach(item => {
        if (ids.includes(item.productId)) {
          const index = this.selectedGoods.findIndex(val => val.productId === item.productId);
          this.selectedGoods.splice(index, 1);
        }
      });
    },
    // 关闭弹窗
    closeDialog () {
      this.search = new Search(this.searchType);
      this.$refs[`${this.searchType}List`].clearSelection();
      this.$emit('closeDialog');
    },
    // 确定选项
    getSelect () {
      // 数组去重
      Array.from(new Set(this.selectedGoods));
      const arr = {};
      arr.option = this.selectedGoods; // 选项赋值，用于筛选框回显
      arr.selected = this.selectedGoods.map(val => val.productId); // 筛选项赋值，用于筛选框回显
      this.$emit('getSelect', arr);
      this.closeDialog();
    }

  }
};
</script>

<style scoped lang="scss">
.tree-header {
  height: 40px;
  background: #f9fafc;
  color: #909399;
  font-size: 12px;
  font-weight: bold;
  line-height: 40px;
  text-align: center;
  border-bottom: 1px solid #ebeef5;
}
.border-bottom {
  border-bottom: 1px solid #ebeef5;
}
</style>
